package com.hsy.crm.web.service.impl;

import com.google.common.collect.Lists;
import com.hsy.crm.web.domain.cm.PageResult;
import com.hsy.crm.web.domain.cm.Unified;
import com.hsy.crm.web.domain.entity.Dict;
import com.hsy.crm.web.domain.ex.ServiceException;
import com.hsy.crm.web.domain.vo.dict.DictPageVo;
import com.hsy.crm.web.domain.vo.dict.DictUpdateVo;
import com.hsy.crm.web.mapper.DictMapper;
import com.hsy.crm.web.service.base.BaseService;
import com.hsy.crm.web.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DictService extends BaseService<Dict> {

    @Autowired
    DictMapper dictMapper;

    public Dict getByCode(Dict dict) {
        if( dict == null ){
            throw new ServiceException("dict is null");
        }
        if( dict.getCustomerId() == null ){
            throw new ServiceException("dict customerId is null");
        }
        if(dict.getCode() == null){
            throw new ServiceException("dict code is null");
        }

        return dictMapper.selectOne(dict);
    }

    public PageResult page(DictPageVo pageVo) {
        PageResult<Dict> pageResult = new PageResult<>();
        List<Dict> dicts = DictUtils.getCustomerDicts(pageVo.getCustomerId());

        List<Dict> tmp = Lists.newArrayList();
        for( Dict dict : dicts ){
            if( dict.getType().intValue() == 1 ){
                tmp.add(dict.toPageDict());
            }
        }

        pageResult.setRows(tmp);
        pageResult.setTotal(tmp.size());
        return pageResult;
    }

    @Transactional
    public Unified<Integer> updateDicts(DictUpdateVo dictUpdateVo){

        for( Dict dict : dictUpdateVo.getDicts() ){
            dict.setCustomerId(dictUpdateVo.getCustomerId());
            dictMapper.updateDict(dict);
        }

        Dict dict = new Dict();
        dict.setCustomerId(dictUpdateVo.getCustomerId());
        DictUtils.setDicts(dictUpdateVo.getCustomerId(),dictMapper.selectDicts(dict));

        return Unified.newInstance();
    }

}
